package model

import (
	"encoding/json"
	"errors"
	"time"
	"unicode/utf8"
)

const (
	ArticleStateUnAudit  = iota // 文章未审核
	ArticleStateHadAudit        // 文章审核通过
	ArticleStateOffline         // 文章审核拒绝
	ArticleStateUserDel         // 文章作者已删除
)

type Article struct {
	HTML      string
	Aid       int       `json:"aid" db:"aid"`
	Sn        uint64    `json:"sn" db:"sn"`
	Title     string    `json:"title" db:"title"`
	UID       uint64    `json:"uid" db:"uid"`
	Cover     string    `json:"cover" db:"cover"`
	Content   string    `json:"content" db:"content"`
	Tags      string    `json:"tags" db:"tags"`
	Words     int       `json:"words" db:"words"`
	State     uint8     `json:"state" db:"state"`
	CreatedAt time.Time `json:"created_at" db:"created_at"`
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}

type ArticleEx struct {
	ArticleSn uint64    `json:"article_sn" db:"article_sn"`
	ViewNum   int       `json:"view_num" db:"view_num"`
	CmtNum    int       `json:"cmt_num" db:"cmt_num"`
	ZanNum    int       `json:"zan_num" db:"zan_num"`
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}

// UnmarshalJSON SignUpForm 类型 自定义 JSON 反序列化的方法
func (s *Article) UnmarshalJSON(data []byte) (err error) {
	required := struct {
		Title   string `json:"title"`
		Content string `json:"content"`
		Tags    string `json:"tags"`
		Words   int    `json:"words"`
		State   uint8  `json:"state"`
	}{}
	err = json.Unmarshal(data, &required)
	if err != nil {
		return
	} else if len(required.Title) == 0 {
		err = errors.New("缺少必填字段 文章标题")
	} else if len(required.Content) == 0 {
		err = errors.New("缺少必填字段 文章内容")
	} else {
		s.Title = required.Title
		s.Content = required.Content
		s.State = 1
		s.Words = utf8.RuneCountInString(required.Content)
		if len(required.Tags) > 0 {
			s.Tags = required.Tags
		}
	}
	return
}

type ArticleInfo struct {
	Article
	ArticleEx
}

// 文章统计信息
type ArticleState struct {
	Chars   int
	Reading string
}

// TOC 文章目录
type Catalog struct {
	Items []*Item
}

type Item struct {
	Level int
	Text  string
	ID    string

	Child []*Item
}

type ApiArticle struct {
	ArticleInfo
	AuthorName string `json:"author_name"`
}

type ApiArticleList struct {
	ArticleList []*ApiArticle `json:"article_list"`
	TotalCount  int           `json:"total_count"`
}
